package dongshi.daddy.simplefactory.spi;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

public class SimpleFactory {
    /*static final int PRODUCT_A = 1;
    static final int PRODUCT_B = 2;
    static final int PRODUCT_C = 3;
    static final int PRODUCT_D = 4;*/
    private static Map<Integer, Product> productMap = new HashMap<>();

    static {
        ServiceLoader<Product> load = ServiceLoader.load(Product.class);
        Iterator<Product> iterator = load.iterator();
        while (iterator.hasNext()) {
            Product next = iterator.next();
            int id = next.getClass().getAnnotation(Key.class).id();
            productMap.put(id, next);
        }
    }

    public static Product makeProduct(int kind) {
        /*if (kind == PRODUCT_A) return new ConcreteProduct1();
        if (kind == PRODUCT_B) return new ConcreteProduct2();
        if (kind == PRODUCT_C) return new ConcreteProduct3();
        if (kind == PRODUCT_D) return new ConcreteProduct4();*/
        return productMap.get(kind);
    }
}
